package de.hmm.hwip.ipc.service;

import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

import android.os.Bundle;

import de.hmm.hwip.ipc.api.IipcToAndroid;
import de.hmm.hwip.ipc.api.IipcToOsgi;

/**
 * OSGi Interprocess communication service
 * Gets data via Interface
 * 
 * @author johannes mendel
 * @version 03.09.2012
 *
 */
public class Activator implements BundleActivator{

	/**
	 * OSGi-Service Interface Iipc
	 */
	static IipcToAndroid androidService;
	
	IipcToOsgi osgiService;
	
	/**
	 * service Tracker to the IPC
	 */
	private ServiceTracker serviceTracker;

	@Override
	public void start(BundleContext context) throws Exception {
		System.out.println("OSGi-Service - Interprocess communication - started");		
		
		serviceTracker = new ServiceTracker(context, IipcToAndroid.class.getName(), null);
		serviceTracker.open();
		androidService = (IipcToAndroid) serviceTracker.getService();
		
		osgiService = new IpcImpl();
		
		// register the service
        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put( org.osgi.framework.Constants.SERVICE_PID, IipcToOsgi.class.getName());
        params.put( org.osgi.framework.Constants.SERVICE_DESCRIPTION,"Provides IPC Service");
        context.registerService(IipcToOsgi.class.getName(), osgiService, params);
	}

	@Override
	public void stop(BundleContext arg0) throws Exception {
		//send message to service that OSGi-Service has stopped
		System.out.println("OSGi-Service - Interprocess communication - stopped");	
		
	}
	
	public static void sendMessageToAndroid(Bundle bundle){
		
		System.out.println("send back bundle");
		if(androidService != null)
			androidService.message(bundle);
		else
			System.out.println("IPC Service back to android is " + androidService);
	}
}
